package com.apt.common;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBUtility {
	
	public static Connection getConnection() throws AptException
	{
		
		Connection conn = null;
		
			Context initContext;
			try {
				initContext = new InitialContext();
				Context envContext = (Context) initContext.lookup("java:/comp/env");
				DataSource ds = (DataSource) envContext.lookup("jdbc/AptDB");
				if(ds == null )
				{
					throw new AptException("DataSource configuration is incorrect!");
					
				}
				
				conn = ds.getConnection();
				conn.setAutoCommit(false);
				//System.out.println("Connection is:"+ conn);
			
			} catch (NamingException e) {	
				
				e.printStackTrace();
				throw new AptException("Unable to look up datasource.Pls see log file for details");
			}
			catch(SQLException ex)
			{
				ex.printStackTrace();
				throw new AptException("Unable to create the connection object.Pls see log file for details");
				
			}
			return conn;
		
	}
	public static void cleanUp(Connection conn)
	{
		if(conn != null )
		{
			try {
				conn.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
			
			
		}
		
		
	}

}
